package com.boyinet.activation.security.filter;

import com.boyinet.activation.util.JsonUtils;
import com.boyinet.activation.util.TokenManager;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * token 认证过滤器
 *
 * @author lengchunyun
 */
public class TokenAuthFilter extends BasicAuthenticationFilter {

    private final TokenManager tokenManager;
    private final StringRedisTemplate stringRedisTemplate;

    public TokenAuthFilter(AuthenticationManager authenticationManager, TokenManager tokenManager, StringRedisTemplate stringRedisTemplate) {
        super(authenticationManager);
        this.tokenManager = tokenManager;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException, AuthenticationException {
        //获取当前认证成功用户权限信息
        UsernamePasswordAuthenticationToken authRequest = getAuthentication(request);
        //判断如果有权限信息，放到权限上下文中
        if (authRequest != null) {
            SecurityContextHolder.getContext().setAuthentication(authRequest);
        } else {
            throw new AuthenticationCredentialsNotFoundException("token is empty");
        }
        chain.doFilter(request, response);
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) throws AuthenticationException {
        //从header获取token
        String token = request.getHeader("token");
        if (StringUtils.isNoneBlank(token)) {
            //从token获取用户名
            String username = tokenManager.getUserFromToken(token);
            //从redis获取对应权限列表
            String json = stringRedisTemplate.opsForValue().get(username);
            List<String> permissionValueList = JsonUtils.parseList(json, String.class);
            Collection<GrantedAuthority> authority = new ArrayList<>();
            if (permissionValueList != null) {
                for (String permissionValue : permissionValueList) {
                    SimpleGrantedAuthority auth = new SimpleGrantedAuthority(permissionValue);
                    authority.add(auth);
                }
                return new UsernamePasswordAuthenticationToken(username, token, authority);
            }
        }
        return null;
    }

}
